<template>
  <view class="menu flex-column">
    <BaseNavBar></BaseNavBar>
    <view class="menu-wrap">
      <view
        class="search flex pl-22"
        :style="{
          marginTop: capsuleInfo?.top - safeAreaInsets?.top + 'px',
          width: capsuleInfo?.left - 50 + 'px',
        }"
      >
        <wd-input
          v-model="searchValue"
          prefix-icon="search"
          placeholder="请输入菜名"
          use-suffix-slot
          @focus="handleFocus"
        >
          <template #suffix>
            <view style="position: relative">
              <wd-button size="small" plain>搜索</wd-button>
            </view>
          </template>
        </wd-input>
      </view>
      <view class="banner mt-10">
        <img
          src="https://sushu-1331835118.cos.ap-nanjing.myqcloud.com/applet-images/banner.jpg"
        />
      </view>
      <view class="navbar pl-20 pr-20 mt-32 flex">
        <view
          :class="[
            'navbar-item flex-center',
            { active: index === currentIndex },
            { 'ml-24': index !== 0 },
          ]"
          v-for="(item, index) of navList"
          :key="index"
          @click="changeNavBar(item, index)"
        >
          <wd-img :width="24" :height="24" enable-preview :src="item.url" />
          <view class="navbar-item-text">{{ item.text }}</view>
        </view>
      </view>
    </view>

    <template v-if="currentIndex === 0">
      <view class="main-wrap flex">
        <view class="slot-white"></view>
        <view class="left-wrap">
          <view class="dish-type flex-column">
            <view
              :class="[
                'type-item flex-center',
                { active: activeTypeIndex === index },
              ]"
              v-for="(item, index) of typeList"
              :key="index"
              @click="changeType(item, index)"
            >
              <span>{{ item.name }}</span>
            </view>
          </view>
        </view>
        <view class="right-wrap ml-32 pb-32">
          <view class="dish-list mr-32">
            <DishItem
              v-for="(item, index) of itemList"
              :key="item.name"
              :item-info="item"
              :class="['flex-column-center', { 'mt-16': index !== 0 }]"
              style="
                padding: 32rpx;
                box-sizing: border-box;
                background-color: #fff;
              "
            >
              <template #rightSlot>
                <view :class="['operate', { rank: index < 3 }]">
                  <wd-icon
                    name="add"
                    size="16px"
                    color="#ff6b6b"
                    @click="joinMenu(item)"
                    v-if="!nameList.map((n) => n.name).includes(item.name)"
                  ></wd-icon>
                  <wd-icon
                    name="remove"
                    size="16px"
                    @click="joinMenu(item)"
                    v-else
                  ></wd-icon>
                </view>
              </template>
            </DishItem>
          </view>
        </view>
      </view>
    </template>

    <view class="often" v-else-if="currentIndex === 1">
      <OftenOrder :hasInList="nameList" @addNameList="addNameList" />
    </view>

    <view class="history" v-else-if="currentIndex === 2">
      <HistoryOrder />
    </view>
    <view class="comment" v-else>
      <Comment />
    </view>

    <view class="sure-button" v-if="[0, 1].includes(currentIndex)">
      <view class="sure-button-wrap flex">
        <view class="choose-wrap flex-column-center" @click="showHasChoose">
          <wd-badge :modelValue="nameList.length"
            ><img src="../../static/images/food.svg"
          /></wd-badge>
          <view class="add-dish p-16">
            <view class="tips">tips:&nbsp;</view>
            <span class="search">左上角可搜索或添加~</span>
          </view>
        </view>
        <wd-button :disabled="btnDisabled" @click="chooseOk">选好了</wd-button>
      </view>
    </view>
    <wd-overlay :show="hasChooseShow" @click="hasChooseShow = false">
      <view class="has-choose-dish" @click.stop="() => {}">
        <view class="header flex">
          <wd-checkbox v-model="allDish" @change="changeAllDish" size="large"
            >已加入菜单（{{ nameList.length }}件）</wd-checkbox
          >
          <view class="reset flex" @click="resetDish">
            <wd-icon name="delete-thin" size="16px"></wd-icon>
            <span class="ml-8">清空菜单</span>
          </view>
        </view>

        <view class="dish-list" v-if="nameList.length !== 0">
          <view
            v-for="item of nameList"
            :key="item.name"
            class="dish-list-item flex-column-center mt-32"
          >
            <wd-checkbox v-model="item.flag" size="large"></wd-checkbox>
            <view class="dish-info flex ml-16">
              <view class="dish-img">
                <wd-img :width="66" :height="66" :src="item.url" round />
              </view>
              <view class="dish-info-wrap flex-column ml-32">
                <view class="name">{{ item.name }}</view>
                <view class="has-num mt-8 flex">
                  <span>本月已点{{ item.monthTime }}次</span>
                </view>
                <view class="method mt-8">
                  <wd-tag type="success" round @click="goToMethod(item)"
                    >做法</wd-tag
                  >
                </view>
              </view>
              <view class="num">
                <wd-input-number v-model="item.num" min="0" />
              </view>
            </view>
          </view>
        </view>
        <view class="empty flex-center" v-else>这里空空的~</view>
      </view>
    </wd-overlay>
  </view>
</template>

<script>
import { defineComponent } from "vue";
import { useDishList } from "../../store/dishList";

export default defineComponent({
  onShareAppMessage: async () => {
    let dishItem = useDishList();
    addOrderList({
      list: dishItem.list.map((item) => item.name).join(","),
      url: dishItem.list.map((item) => item.url).join(","),
    }).then((res) => {
      console.log(res, "===");
      dishItem.clearItem();
    });
    return {
      title: "明日餐食",
      path: "/pages/menu/selected",
      imageUrl: "/static/images/food.png",
    };
  },
});
</script>

<script setup>
import { computed, onMounted, ref, watch } from "vue";
import { onShow } from "@dcloudio/uni-app";

import { getMenuList, addOrderList } from "../../api/menu";
import tab from "../../utils/tab";
import { toast, showConfirm } from "../../utils/common";
import { unionById } from "../../utils/util";
import { useDishList } from "../../store/dishList";
import DishItem from "./dishItem.vue";
import HistoryOrder from "./pageComponents/historyOrder.vue";
import Comment from "./pageComponents/comment.vue";
import OftenOrder from "./pageComponents/oftenOrder.vue";

let dishItem = useDishList();

onShow(() => {
  if (dishItem.list.length !== 0) {
    dishItem.list.forEach((item) => {
      if (!nameList.value.find((n) => n.name === item.name)) {
        nameList.value.push(item);
      }
    });
  }
});

watch(
  () => dishItem.list,
  (nv, ov) => {
    if (nv.length === 0) {
      nameList.value = [];
    }
  },
  {
    deep: true,
  }
);

const { safeAreaInsets } = uni.getSystemInfoSync();
let capsuleInfo = uni.getMenuButtonBoundingClientRect();

const searchValue = ref(null);

const handleFocus = () => {
  console.log("input focus");
  tab.navigateTo("search");
};

onMounted(() => {
  getMenuList().then((res) => {
    if (res.code === 0) {
      res.data.forEach((item, index) => {
        if (index < 3) {
          item.rank = index + 1;
        }
      });
      itemList.value = res.data;
    }
  });
});

const currentIndex = ref(0);
const navList = ref([
  {
    text: "今日食单",
    url: "https://sushu-1331835118.cos.ap-nanjing.myqcloud.com/applet-images/nav1.jpg",
  },
  {
    text: "心头好味",
    url: "https://sushu-1331835118.cos.ap-nanjing.myqcloud.com/applet-images/nav2.jpg",
  },
  {
    text: "食光记忆",
    url: "https://sushu-1331835118.cos.ap-nanjing.myqcloud.com/applet-images/nav3.png",
  },
  {
    text: "味觉笔记",
    url: "https://sushu-1331835118.cos.ap-nanjing.myqcloud.com/applet-images/nav4.jpg",
  },
]);

const changeNavBar = (item, index) => {
  currentIndex.value = index;
};

const activeTypeIndex = ref(0);
const typeList = ref([
  {
    name: "全部",
    type: "",
  },
  {
    name: "海鲜",
    type: "3",
  },
  {
    name: "荤菜",
    type: "1",
  },
  {
    name: "蔬菜",
    type: "2",
  },
  {
    name: "小食",
    type: "4",
  },
  {
    name: "水果",
    type: "5",
  },
]);
const changeType = (item, index) => {
  activeTypeIndex.value = index;
  getMenuList({
    type: item.type,
  }).then((res) => {
    if (res.code === 0) {
      itemList.value = res.data;
    }
  });
};

const itemList = ref([]);

const nameList = ref([]);
function addNameList(list) {
  nameList.value = unionById(nameList.value, list);
}

function joinMenu(item) {
  let cIndex = nameList.value.findIndex((n) => n.name === item.name);
  let dIndex = dishItem.list.findIndex((d) => d.name === item.name);
  if (dIndex !== -1) {
    dishItem.removeItem(dIndex);
  }
  if (cIndex !== -1) {
    nameList.value.splice(cIndex, 1);
    return;
  }
  if (nameList.value.length === 4) {
    toast({
      title: "一次最多只能选四个菜哦~",
      icon: "error",
    });
    return;
  }
  nameList.value.push({
    ...item,
    num: 1,
    flag: true,
  });
  dishItem.addItem({
    ...item,
    num: 1,
    flag: true,
  });
}

const btnDisabled = computed(() => nameList.value.length === 0);
const hasChooseShow = ref(false);
const showHasChoose = () => {
  hasChooseShow.value = !hasChooseShow.value;
  console.log(hasChooseShow);
};
const allDish = ref(true);
function changeAllDish() {}
const resetDish = () => {
  showConfirm({
    content: "确认清空菜单嘛?",
    success: (res) => {
      console.log(res);
      if (res.confirm) {
        nameList.value = [];
      }
    },
  });
};

function chooseOk() {
  addOrderList({
    list: dishItem.list.map((item) => item.name).join(","),
    url: dishItem.list.map((item) => item.url).join(","),
  }).then((res) => {
    if (res.code === 0) {
      dishItem.clearItem();
      toast({
        title: "您已下单，可前往食光记忆中查看~",
      });
    }
  });
}
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
